<template>
  <div class="common-layout">
    <el-container>
      <el-main>
        <div class="search-bar">
          <el-input v-model="searchQuery" placeholder="输入姓名/手机号" style="width: 240px; margin-right: 16px" clearable
            @input="handleSearch" />
          <el-select v-model="selectedDoctor" placeholder="选择医生" clearable @change="handleSearch"
            style="width: 180px; margin-right: 16px">
            <el-option v-for="doctor in doctors" :key="doctor.doctorId" :label="doctor.doctorName"
              :value="doctor.doctorId" />
          </el-select>
        </div>

        <el-table :data="tableData" :row-class-name="tableRowClassName" v-loading="loading" style="width: 100%">
          <el-table-column prop="reservationId" label="预约ID" />

          <el-table-column label="宠物名称">
            <template #default="{ row }">{{ row.petName || '未知' }}</template>
          </el-table-column>

          <el-table-column label="类型">
            <template #default="{ row }">{{ row.petType || '未知' }}</template>
          </el-table-column>

          <el-table-column label="顾客姓名">
            <template #default="{ row }">{{ row.nickname || '未知' }}</template>
          </el-table-column>

          <el-table-column label="联系方式">
            <template #default="{ row }">{{ row.phone || '未知' }}</template>
          </el-table-column>

          <el-table-column label="医生">
            <template #default="{ row }">{{ row.doctorName || '未知' }}</template>
          </el-table-column>

          <el-table-column label="预约日期">
            <template #default="{ row }">{{ row.reservationDate || '未知' }}</template>
          </el-table-column>

          <el-table-column label="时间段">
            <template #default="{ row }">{{ row.reservationTime || '未知' }}</template>
          </el-table-column>

          <el-table-column prop="status" label="状态">
            <template #default="{ row }">
              <el-tag :type="statusTagType[row.status]">
                {{ statusMap[row.status] || '未知' }}
              </el-tag>
            </template>
          </el-table-column>

          <!-- 操作列 -->
          <el-table-column label="操作" width="180">

            <template #default="{ row }">
              <el-button type="primary" size="small" @click="openEditForm(row)">修改预约</el-button>

              <!-- 添加确认提示框 -->
              <el-popconfirm title="确认要取消该预约吗？" confirm-button-text="确认" cancel-button-text="再想想"
                @confirm="handelCancel(row.reservationId)" v-if="row.status != 4">
                <template #reference>
                  <el-button type="danger" size="small">取消预约</el-button>
                </template>
              </el-popconfirm>
            </template>

          </el-table-column>
        </el-table>

        <el-pagination background layout="prev, pager, next" :total="total" :page-size="pageSize"
          :current-page="currentPage" @current-change="handlePageChange" class="mt-4" />
      </el-main>
    </el-container>

    <!-- 表单弹窗 -->
    <AppointmentDialog v-model:visible="dialogVisible" :form-data="editingFormData" :doctor="editingDoctor" mode="edit"
      @updated="fetchAppointmentList" />


  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import AppointmentDialog from '../register/AppointmentDialog.vue'
import { getDoctorList, getAppointmentPageList } from '@/api/appointment'
import { ElMessage } from 'element-plus'
import { appointmentCancel } from '@/api/appointment'

interface Reservation {
  reservationId: string
  clientId: string
  petName: string
  petType: string
  phone: string
  nickname: string
  doctorId: number
  doctorName?: string
  reservationDate: string
  reservationTime: string
  status: number
}

// 数据源
const tableData = ref<Reservation[]>([])
const doctors = ref()

const searchQuery = ref("")
const selectedDoctor = ref("")
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)
const loading = ref(false)

// 状态映射
const statusMap = {
  1: '预约中',
  2: '接诊中',
  3: '完成',
  4: '取消'
}
const statusTagType = {
  1: 'primary',
  2: 'warning',
  3: 'success',
  4: 'danger'
}

// 获取医生列表
const fetchDoctorList = async () => {
  try {
    const res = await getDoctorList()
    doctors.value = res.data || []
  } catch (error) {
    console.error(error)
    ElMessage.error('获取医生列表失败')
  }
}

// 获取预约列表
const fetchAppointmentList = async () => {
  try {
    loading.value = true
    const params = {
      current: currentPage.value,
      pageSize: pageSize.value,
      searchQuery: searchQuery.value,
      doctorId: selectedDoctor.value
    }
    const res = await getAppointmentPageList(params)
    const list = res.data.data || []

    // doctorId => doctorName 映射
    list.forEach(item => {
      const matchedDoctor = doctors.value.find(d => String(d.doctorId) === String(item.doctorId))
      item.doctorName = matchedDoctor?.doctorName || '未知'
    })
    tableData.value = list
    total.value = res.data.total || 0
  } catch (error) {
    console.error(error)
    ElMessage.error('获取预约列表失败')
  } finally {
    loading.value = false
  }
}

// 初始化
onMounted(async () => {
  await fetchDoctorList()
  await fetchAppointmentList()
})

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchAppointmentList()
}

// 分页
const handlePageChange = (page: number) => {
  currentPage.value = page
  fetchAppointmentList()
}

// 表格行样式
const tableRowClassName = ({ row }: { row: Reservation }) => {
  switch (row.status) {
    case 1: return 'status-pending'
    case 2: return 'status-processing'
    case 3: return 'status-completed'
    case 4: return 'status-cancelled'
    default: return ''
  }
}

//取消预约
const handelCancel = async (id: string) => {
  try {
    const res = await appointmentCancel(id, '4')
    if (res.code === 200) {
      ElMessage.success('取消预约成功')
      fetchAppointmentList()
    } else {
      ElMessage.error('取消预约失败')
    }
  } catch (error) {
    console.error(error)
    ElMessage.error('取消预约失败')
  }
}

// 编辑弹窗
const dialogVisible = ref(false)
const editingDoctor = ref<any>(null)
const editingFormData = ref<any>(null)

const openEditForm = (row: Reservation) => {
  dialogVisible.value = true
  editingDoctor.value = {
    doctorId: row.doctorId || '',
    doctorName: row.doctorName || '未知'
  }
  editingFormData.value = { ...row }
}
</script>

<style scoped>
.search-bar {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.el-table .status-pending {
  --el-table-tr-bg-color: var(--el-color-primary-light-9);
}

.el-table .status-processing {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}

.el-table .status-completed {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}

.el-table .status-cancelled {
  --el-table-tr-bg-color: var(--el-color-danger-light-9);
}

.mt-4 {
  margin-top: 20px;
  justify-content: flex-end;
}

::v-deep(.el-table__row) {
  height: 60px;
}
</style>